<template>
	<el-dialog
		:title="title"
		:center="true"
		width="1000px"
		:append-to-body="true"
		:close-on-click-modal="false"
		:visible.sync="isShow"
	>
		<div class="btn-box">
			<el-button type="primary" :disabled="!selectItems.length" @click="onDelete(selectItems)">删除</el-button>
		</div>
		<el-table :stripe="true" :data="questionList" :cell-style="tableCellStyle">
			<el-table-column width="55" align="center">
				<!--下面是表头的复选框，使用插槽header。实现全选以及部分选择-->
				<template #header>
					<el-checkbox
						v-model="isAllCheck"
						:indeterminate="headerIndeterminate"
						:disabled="!questionList.length"
						@change="handleCheckAllChange"
					/>
				</template>
				<template slot-scope="scope">
					<el-checkbox
						v-if="!scope.row.parentQuestionId"
						v-model="scope.row.isChecked"
						:key="getRowKeys(scope.row)"
						:indeterminate="scope.row.indeterminate"
						@change="rowSelectionChange(scope.row,scope.$index)"
					/>
				</template>
			</el-table-column>
			<el-table-column
				class="theme-border-color"
				width="55"
				label="序号"
				prop="qIndex"
				v-slot="{ row }"
				align="center"
			>
				{{ row.parentQuestionId?'':row.qIndex }}
			</el-table-column>
			<el-table-column prop="questionContent" label="试题内容">
				<template slot-scope="scope">
					<div class="question-detail">
						<el-checkbox
							v-if="scope.row.parentQuestionId"
							v-model="scope.row.isChecked"
							:key="getRowKeys(scope.row)"
							@change="subSelectionChange(scope.row)"
						/>
						<question-show
							:question="scope.row"
							@sub-selection-change="(checked,index)=>subSelectionChange(checked,index,scope.$index)"
						/>
					</div>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="110px" align="center">
				<template #default="{ row }">
					<el-button type="text" @click="onDelete([row])">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
	</el-dialog>
</template>

<script>
	import QuestionShow from "../qb-show/index";
	export default {
		props: {
			//是否显示弹窗
			visibly: {
				type: Boolean,
				default: false
			},
			title: {
				type: String,
				default: "已关联试题"
			},
			list: {
				type: Array,
				default: () => []
			},
			upperDeal: {
				//是否上级处理删除逻辑
				type: Boolean,
				default: false
			}
		},
		components: {
			QuestionShow
		},
		data() {
			return {
				isShow: this.visibly, // 内部的是否显示弹窗
				selectItems: [], // 当前选中的选项列表
				headerIndeterminate: false,
				isAllCheck: false,
				questionList: []
			};
		},
		watch: {
			// 内部和外部的变量双向绑定
			isShow(val) {
				this.$emit("update:visibly", val);
			},
			list: {
				handler(val) {
					this.questionList = JSON.parse(JSON.stringify(val));
				},
				immediate: true
			},
			visibly(val) {
				this.isShow = val;
			}
		},
		methods: {
			//获取id
			getRowKeys(question) {
				if (question.questionstemDetail && question.questionstemDetail.questionstemId) {
					//大题
					return question.questionstemDetail.questionstemId;
				} else if (question.questionstemDetail) {
					// 独立题型
					return question.questionList[0].questionDetail.questionId;
				} else {
					//大题下小题
					return question.questionDetail.questionId;
				}
			},
			// 控制表格列的边框样式
			tableCellStyle({ row, columnIndex }) {
				//组合题不显示前几列不显示下边框
				const cond1 = row.parentQuestionId && !row.isSqLast; //小题且不是最后一道小题
				const cond2 = row.questionstemDetail && row.questionstemDetail.questionstemId; //是组合题型
				const cond3 = columnIndex == 0 || columnIndex == 1; //选择框,序号,资源ID
				let result = {};
				if ((cond2 || cond1) && cond3) {
					result["border-bottom"] = "none";
				}
				result["background"] = "transparent";
				return result;
			},
			//表头全选和全不选
			handleCheckAllChange(isAllCheck) {
				this.headerIndeterminate = false;
				this.questionList = this.questionList.map((question) => {
					question.isChecked = isAllCheck;
					return question;
				});
				this.selectionChange();
			},
			//单行独立题型和大题-选中改变
			rowSelectionChange(question, index) {
				if (question.questionstemDetail && question.questionstemDetail.questionstemId) {
					const subQuestionList = this.questionList.filter(
						(item) => item.parentQuestionId === question.questionstemDetail.questionstemId
					);
					subQuestionList.forEach((subQuestion) => {
						subQuestion.isChecked = question.isChecked;
					});
					question.indeterminate = false;
				}
				this.$set(this.questionList, index, question);
				this.selectionChange();
				this.updateIsCheckedAll();
			},
			//更新选中的题目信息
			selectionChange() {
				let selectList = [];
				const questionList = this.questionList.filter(
					(question) => !(question.questionstemDetail && question.questionstemDetail.questionstemId)
				);
				//选中的试题
				selectList = questionList.filter((question) => question.isChecked);
				//检索出当前已缓存并且当前表格中不存在的选项
				const arr = this.selectItems.filter((i1) => {
					let questionId = this.getRowKeys(i1);
					return !questionList.some((i2) => {
						const i2Id = this.getRowKeys(i2);
						return questionId === i2Id;
					});
				});
				this.selectItems = [...arr, ...selectList];
			},
			//子级改变
			subSelectionChange(subQuestion) {
				const question = this.questionList[subQuestion.parentIndex];
				this.updateCombinationChecked(question);
				this.selectionChange();
				this.updateIsCheckedAll();
			},
			//更新表头选中状态
			updateIsCheckedAll() {
				if (!this.questionList.length) {
					this.isAllCheck = false;
					this.headerIndeterminate = false;
					return;
				}
				//是否全选
				const isAllCheck = this.questionList.every((question) => question.isChecked);
				//是否有选中
				const hasCheck = this.questionList.some((question) => question.isChecked);
				this.isAllCheck = isAllCheck;
				this.headerIndeterminate = !isAllCheck && hasCheck;
			},
			updateCombinationChecked(question) {
				const subQuestionList = this.questionList.filter((item) => {
					return item.parentQuestionId === this.getRowKeys(question);
				});
				const qIndex = this.questionList.findIndex((item) => {
					return this.getRowKeys(item) === this.getRowKeys(question);
				});
				const isAllCheck = subQuestionList.every((subQuestion) => {
					return subQuestion.isChecked;
				});
				//是否有选中
				const hasCheck = subQuestionList.some((subQuestion) => {
					return subQuestion.isChecked;
				});
				question.indeterminate = !isAllCheck && hasCheck;
				question.isChecked = isAllCheck;
				this.$set(this.questionList, qIndex, question);
			},
			// 点击删除
			onDelete(arr) {
				let resultArr = this.questionList.filter((i1) => {
					let questionId = this.getRowKeys(i1);
					return !arr.some((i2) => {
						let questionId2 = this.getRowKeys(i2);
						return questionId2 === questionId || questionId2 === i1.parentQuestionId;
					});
				});
				//过滤没有小题的大题
				resultArr = resultArr.filter((i1) => {
					if (i1.questionstemDetail && i1.questionstemDetail.questionstemId) {
						return resultArr.some((i2) => {
							return i2.parentQuestionId === this.getRowKeys(i1);
						});
					}
					return true;
				});
				const list = resultArr.filter((i1) => {
					return !(i1.questionstemDetail && i1.questionstemDetail.questionstemId);
				});

				resultArr.forEach((question, index) => {
					if (question.questionstemDetail && question.questionstemDetail.questionstemId) {
						question.qIndex = index + 1;
						question.questionList.forEach((subQuestion, sIndex) => {
							subQuestion.qIndex = index + 1 + "-" + (sIndex + 1);
							subQuestion.parentIndex = index;
							subQuestion.parentQuestionId = question.questionstemDetail.questionstemId;
							subQuestion.isSqLast = sIndex === question.questionList.length - 1; //是不是最后一道小题
						});
					} else {
						question.qIndex = index + 1;
					}
				});

                this.$confirm("确定要删除试题吗？", "删除提示", {
                    type: "warning"
                }).then(() => {
                   if (this.upperDeal) {
                        this.$emit("delete", list);
                    } else {
                        this.$message.success("试题删除成功");
                        this.$emit("change", resultArr, list);
                        //更新大题的选中状态
                        this.questionList = resultArr;
                        this.questionList.forEach((item) => {
                            if (item.questionstemDetail && item.questionstemDetail.questionstemId) {
                                this.updateCombinationChecked(item);
                            }
                        });
                        this.selectItems = this.selectItems.filter((i1) => {
                            let questionId = this.getRowKeys(i1);
                            return !arr.some((i2) => {
                                const i2Id = this.getRowKeys(i2);
                                return questionId === i2Id;
                            });
                        });
                        this.selectionChange();
                        this.updateIsCheckedAll();
                    }
                });

			}
		}
	};
</script>

<style lang="less" scoped>
	.btn-box {
		margin-bottom: 20px;
		text-align: right;
	}
	.star-box {
		display: flex;
		align-items: center;

		.img {
			margin: 0 3px;
		}
	}

	.hint-box {
		margin-top: 20px;
		font-size: 14px;
	}
	/deep/ .el-dialog {
		margin-top: 0 !important;
		height: 100vh;
		overflow-y: auto;
		.el-table__body-wrapper {
			height: calc(100vh - 204px);
			overflow-y: auto;
		}
		td {
			vertical-align: top;
		}
	}
	/deep/ .question-detail {
		display: flex;
		.el-checkbox {
			margin-right: 10px;
		}
	}
</style>
